package com.samnative.pineapple.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.PutFileUtils;
import com.bumptech.glide.Glide;
import com.samnative.pineapple.entity.AliPostImginfoModel;
import com.samnative.pineapple.entity.UserModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.google.gson.Gson;
import com.shashank.sony.fancytoastlib.FancyToast;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;


/**
 * 实名认证
 * Created by Wy on 2018/4/26.
 */

public class AuthNameActivity extends BaseActivity implements View.OnClickListener {

    private final static int frontCode = 100;
    private final static int sideCode = 200;

    /**
     * 个人数据
     */
    private UserModel userModel = null;

    private String frontUrl = "";//证明照片
    private String sideUrl = "";//背面照片
    private ImageView ivFront, ivSide;
    private AliPostImginfoModel aliModel;
    private LinearLayout ll_image;
    private LinearLayout ll_front;
    private LinearLayout ll_side;

    private TextView tv_reason;

    private TextView tv_other_set;
    private EditText et_last;
    private EditText et_name;
    private TextView tv_sex_set;
    private TextView tv_country_set;
    private EditText et_passport;
    private RelativeLayout rl_last;
    private RelativeLayout rl_name;
    private LinearLayout ll_other;

    private EditText et_real_name;
    private EditText et_id_card;
    private RelativeLayout rl_real_name;
    private RelativeLayout rl_card;

    private TextView tv_submit;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_authname;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        find(R.id.rl_back).setOnClickListener(this);
        ivFront = find(R.id.iv_front);
        ivSide = find(R.id.iv_side);

        et_real_name = find(R.id.et_real_name);
        et_id_card = find(R.id.et_id_card);

        tv_other_set = find(R.id.tv_other_set);
        et_last = find(R.id.et_last);
        et_name = find(R.id.et_name);
        tv_sex_set = find(R.id.tv_sex_set);
        tv_country_set = find(R.id.tv_country_set);
        et_passport = find(R.id.et_passport);

        rl_last = find(R.id.rl_last);
        rl_name = find(R.id.rl_name);
        ll_other = find(R.id.ll_other);
        rl_real_name = find(R.id.rl_real_name);
        rl_card = find(R.id.rl_card);

        tv_other_set.setOnClickListener(this);
        tv_sex_set.setOnClickListener(this);
        tv_country_set.setOnClickListener(this);

        ll_image = find(R.id.ll_image);
        ll_front = find(R.id.ll_front);
        ll_front.setOnClickListener(this);
        ll_side = find(R.id.ll_side);
        ll_side.setOnClickListener(this);
        tv_reason = find(R.id.tv_reason);
        tv_submit = find(R.id.tv_submit);
        tv_submit.setOnClickListener(this);
        find(R.id.rl_back).setOnClickListener(this);

        userModel = AppPrefer.getUserModel(mContext);

        requestShenhe();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_front://身份证正面
                MultiImageSelector.create().showCamera(true) // 是否显示相机. 默认为显示
                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() // 单选模式 .multi() / 多选模式, 默认模式;
                        .start(this, frontCode);
                break;
            case R.id.ll_side://身份证反面
                MultiImageSelector.create().showCamera(true) // 是否显示相机. 默认为显示
                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() // 单选模式 .multi() / 多选模式, 默认模式;
                        .start(this, sideCode);
                break;
            case R.id.tv_submit://提交
                if (TextUtils.isEmpty(et_real_name.getText().toString().trim())) {
                    FancyToast.showToast(mContext, "请填写真实姓名", FancyToast.WARNING, false);
                    return;
                }
                if (TextUtils.isEmpty(et_id_card.getText().toString().trim())) {
                    FancyToast.showToast(mContext, "请填写身份证号", FancyToast.WARNING, false);
                    return;
                }

                if (TextUtils.isEmpty(frontUrl)) {
                    FancyToast.showToast(mContext, "请上传身份证正面照片", FancyToast.WARNING, false);
                    return;
                }
                if (TextUtils.isEmpty(sideUrl)) {
                    FancyToast.showToast(mContext, "请上传身份证背面照片", FancyToast.WARNING, false);
                    return;
                }
                tv_submit.setEnabled(false);
                submitData();
                break;
            case R.id.rl_back:
                finish();
                break;
            default:
        }
    }

    /**
     * 大陆身份证实名认证
     */
    public void submitData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "user.user.auth");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("realname", et_real_name.getText().toString().trim());
        map.put("idnumber", et_id_card.getText().toString().trim());
        map.put("idcardimg", frontUrl + "," + sideUrl);
        HttpRequest.post((Activity) mContext, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                FancyToast.showToast(mContext, "提交成功", FancyToast.WARNING, false);
                requestUserData();
            }
        });

    }

    /**
     * 获取用户信息
     */
    public void requestUserData() {
        if (AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "").isEmpty()) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("_apiname", "user.index.main");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
                    AppPrefer.getInstance(mContext).put(AppPrefer.userinfo, result.toString());
                    finish();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });
    }

    /**
     * 请求审核结果
     */
    public void requestShenhe() {
        if (AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "").isEmpty()) {
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "user.user.authinfo");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));

        HttpRequest.post(this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result.optJSONObject("data");
                    String remark = jsonData.optString("remark");
                    if (!remark.isEmpty()) {
                        tv_reason.setVisibility(View.VISIBLE);
                        tv_reason.setText(remark);
                    } else {
                        tv_reason.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == frontCode && resultCode == RESULT_OK) {
            List<String> mSelectPath = data
                    .getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            ivFront.setVisibility(View.VISIBLE);
            getPostImgInfo(mSelectPath.get(0), msg -> {
                if (msg.what == 200) {
                    frontUrl = aliModel.getDir() + ".jpeg";
                    Glide.with(mContext)
                            .load(mSelectPath.get(0)) //图片地址
                            .apply(GlideRequestOptions.OPTIONS_600_300)
                            .into(ivFront);
                    ll_front.setVisibility(View.GONE);
                } else {
                    FancyToast.showToast(mContext, "图片上传失败", FancyToast.WARNING, false);
                }
                return false;
            });
        } else if (requestCode == sideCode && resultCode == RESULT_OK) {
            List<String> mSelectPath = data
                    .getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            ivSide.setVisibility(View.VISIBLE);
            getPostImgInfo(mSelectPath.get(0), msg -> {
                if (msg.what == 200) {
                    sideUrl = aliModel.getDir() + ".jpeg";
                    Glide.with(mContext)
                            .load(mSelectPath.get(0)) //图片地址
                            .apply(GlideRequestOptions.OPTIONS_600_300)
                            .into(ivSide);
                    ll_side.setVisibility(View.GONE);
                } else {
                    FancyToast.showToast(mContext, "图片上传失败", FancyToast.WARNING, false);
                }
                return false;
            });
        }
    }


    /**
     * 获取上传图片的连接及参数信息
     */

    public void getPostImgInfo(String certPath, Handler.Callback callBack) {
        Map<String, String> map = new HashMap<>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("_apiname", "sys.upload.policy");

        HttpRequest.post(this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                Gson gson = new Gson();
                try {
                    JSONObject jsonData = result.getJSONObject("data");
                    aliModel = gson.fromJson(jsonData.toString(),
                            AliPostImginfoModel.class);
                    PutFileUtils.putFile(AuthNameActivity.this, aliModel, new File(certPath), ".jpeg", callBack);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
